#!/usr/bin/env python3
"""
自定义游戏数据加载器
支持从JSON格式加载自定义迷宫、BOSS群、线索、技能等
"""

import json
import hashlib
from typing import Dict, List, Tuple, Optional, Any
try:
    from .puzzle_solver import PuzzleSolver
    from .boss_battle_optimizer import BossBattleOptimizer
except ImportError:
    from puzzle_solver import PuzzleSolver
    from boss_battle_optimizer import BossBattleOptimizer

class CustomGameLoader:
    """自定义游戏数据加载器"""
    
    def __init__(self):
        self.maze_data = None
        self.clues = []
        self.boss_group = []
        self.player_skills = []
        self.target_hash = ""
        self.player_coins = 10  # 初始金币
        self.password_attempts = 0
        
    def load_from_json(self, json_data: Dict[str, Any]) -> bool:
        """从JSON数据加载游戏配置"""
        try:
            # 加载迷宫
            if "maze" in json_data:
                self.maze_data = json_data["maze"]
                print(f"✅ 迷宫加载成功: {len(self.maze_data)}x{len(self.maze_data[0])}")
            
            # 加载线索
            if "C" in json_data:
                self.clues = json_data["C"]
                print(f"✅ 线索加载成功: {len(self.clues)}个线索")
                self._describe_clues()
            
            # 加载BOSS群
            if "B" in json_data:
                self.boss_group = json_data["B"]
                print(f"✅ BOSS群加载成功: {len(self.boss_group)}个BOSS")
                print(f"   BOSS血量: {self.boss_group}")
            
            # 加载玩家技能
            if "PlayerSkills" in json_data:
                self.player_skills = json_data["PlayerSkills"]
                print(f"✅ 玩家技能加载成功: {len(self.player_skills)}个技能")
                self._describe_skills()
            
            # 加载目标哈希
            if "L" in json_data:
                self.target_hash = json_data["L"]
                print(f"✅ 目标哈希加载成功")
            
            return True
            
        except Exception as e:
            print(f"❌ 加载失败: {e}")
            return False
    
    def load_from_file(self, filename: str) -> bool:
        """从文件加载游戏配置"""
        try:
            with open(filename, 'r', encoding='utf-8') as f:
                json_data = json.load(f)
            return self.load_from_json(json_data)
        except Exception as e:
            print(f"❌ 文件加载失败: {e}")
            return False
    
    def _describe_clues(self):
        """描述线索内容"""
        print("🔍 线索详情:")
        for i, clue in enumerate(self.clues):
            description = self._parse_clue_description(clue)
            print(f"   线索{i+1}: {clue} -> {description}")
    
    def _parse_clue_description(self, clue: List[int]) -> str:
        """解析线索描述"""
        if len(clue) == 2:
            if clue[0] == -1 and clue[1] == -1:
                return "每位密码为素数且不重复"
            else:
                position = clue[0]
                parity = "偶数" if clue[1] == 0 else "奇数"
                return f"第{position}位是{parity}"
        elif len(clue) == 3:
            for i, digit in enumerate(clue):
                if digit != -1:
                    return f"第{i+1}位是数字{digit}"
        return "未知线索格式"
    
    def _describe_skills(self):
        """描述技能内容"""
        print("⚔️ 玩家技能:")
        for i, skill in enumerate(self.player_skills):
            damage, cooldown = skill
            print(f"   技能{i+1}: 伤害{damage}, 冷却{cooldown}回合")
    
    def get_maze_info(self) -> Dict[str, Any]:
        """获取迷宫信息"""
        if not self.maze_data:
            return {}
        
        size = len(self.maze_data)
        start_pos = None
        exit_pos = None
        boss_positions = []
        resources = {}
        traps = []
        locks = []
        
        # 解析迷宫元素
        for i in range(size):
            for j in range(size):
                cell = self.maze_data[i][j]
                if cell == "S":
                    start_pos = (i, j)
                elif cell == "E":
                    exit_pos = (i, j)
                elif cell == "B":
                    boss_positions.append((i, j))
                elif cell == "G":
                    resources[(i, j)] = 5  # 默认资源值
                elif cell == "T":
                    traps.append((i, j))
                elif cell == "L":
                    locks.append((i, j))
        
        return {
            "size": size,
            "maze_matrix": self.maze_data,
            "start_pos": start_pos,
            "exit_pos": exit_pos,
            "boss_positions": boss_positions,
            "resources": resources,
            "traps": traps,
            "locks": locks
        }
    
    def solve_password_puzzle(self) -> Optional[str]:
        """
        解密码谜题（仅支持带盐值哈希）
        
        返回：
        破解的密码字符串，失败返回None
        """
        if not self.clues or not self.target_hash:
            print("❌ 缺少线索或目标哈希")
            return None
        
        print(f"\n🧩 开始解密码谜题...")
        print(f"💰 当前金币: {self.player_coins}")
        print(f"🔒 使用带盐值哈希验证模式")
        
        # 创建密码解析器
        solver = PuzzleSolver()
        
        # 使用带盐值哈希求解
        result = solver.solve_with_salted_hash(self.clues, self.target_hash)
        
        if result:
            password = ''.join(map(str, result))
            print(f"✅ 密码破解成功: {password}")
            
            # 计算金币消耗（每次哈希验证消耗1金币）
            cost = solver.total_attempts
            self.player_coins -= cost
            self.password_attempts += cost
            
            print(f"💰 金币消耗: {cost}, 剩余: {self.player_coins}")
            return password
        else:
            print(f"❌ 密码破解失败")
            return None
    
    def create_salted_hash_test_case(self, password: str) -> str:
        """
        为指定密码创建带盐值的哈希测试用例
        
        参数：
        password: 要创建哈希的密码
        
        返回：
        带盐值的哈希字符串
        """
        solver = PuzzleSolver()
        return solver.create_salted_test_case(password)
    
    def create_custom_boss_optimizer(self, boss_index: int, player_resources: int) -> Optional[BossBattleOptimizer]:
        """创建自定义BOSS战优化器"""
        if not self.boss_group or boss_index >= len(self.boss_group):
            return None
        
        boss_hp = self.boss_group[boss_index]
        
        # 创建优化器
        optimizer = BossBattleOptimizer(
            initial_boss_hp=boss_hp,
            initial_player_resources=player_resources,
            max_rounds=20
        )
        
        # 如果有自定义技能，覆盖默认技能
        if self.player_skills:
            custom_skills = {}
            for i, (damage, cooldown) in enumerate(self.player_skills):
                skill_name = f"自定义技能{i+1}"
                from .boss_battle_optimizer import Skill
                custom_skills[skill_name] = Skill(
                    name=skill_name,
                    damage=damage,
                    cost=max(1, damage // 3),  # 根据伤害计算消耗
                    cooldown=cooldown,
                    description=f"伤害{damage}, 冷却{cooldown}回合"
                )
            
            # 保留普通攻击
            custom_skills["普通攻击"] = optimizer.skills["普通攻击"]
            optimizer.skills = custom_skills
            
            print(f"🎯 使用自定义技能系统: {len(custom_skills)}个技能")
        
        return optimizer
    
    def simulate_boss_group_battle(self, player_resources: int) -> Dict[str, Any]:
        """模拟BOSS群战斗"""
        if not self.boss_group:
            return {"success": False, "message": "没有BOSS群数据"}
        
        print(f"\n⚔️ 开始BOSS群战斗!")
        print(f"BOSS数量: {len(self.boss_group)}")
        print(f"BOSS血量: {self.boss_group}")
        print(f"玩家资源: {player_resources}")
        
        total_rounds = 0
        all_strategies = []
        current_resources = player_resources
        
        for i, boss_hp in enumerate(self.boss_group):
            print(f"\n👹 挑战BOSS {i+1}/{len(self.boss_group)}")
            print(f"   血量: {boss_hp}")
            print(f"   当前资源: {current_resources}")
            
            optimizer = self.create_custom_boss_optimizer(i, current_resources)
            if not optimizer:
                return {
                    "success": False,
                    "message": f"无法创建BOSS {i+1}的优化器"
                }
            
            result = optimizer.branch_and_bound()
            if not result:
                return {
                    "success": False,
                    "message": f"无法击败BOSS {i+1}，资源不足",
                    "failed_at_boss": i+1,
                    "total_rounds": total_rounds
                }
            
            skill_sequence, rounds = result
            total_rounds += rounds
            all_strategies.append({
                "boss_index": i+1,
                "boss_hp": boss_hp,
                "rounds": rounds,
                "skill_sequence": skill_sequence
            })
            
            print(f"   ✅ 击败! 用时{rounds}回合")
            print(f"   策略: {' -> '.join(skill_sequence[:3])}...")
            
            # 计算剩余资源（简化：假设每场战斗后资源消耗殆尽）
            current_resources = max(0, current_resources - boss_hp // 5)
        
        return {
            "success": True,
            "message": f"成功击败所有{len(self.boss_group)}个BOSS!",
            "total_rounds": total_rounds,
            "strategies": all_strategies,
            "boss_count": len(self.boss_group)
        }
    
    def get_game_summary(self) -> Dict[str, Any]:
        """获取游戏总结"""
        maze_info = self.get_maze_info()
        
        return {
            "maze_loaded": bool(self.maze_data),
            "maze_size": maze_info.get("size", 0),
            "boss_count": len(self.boss_group),
            "clue_count": len(self.clues),
            "skill_count": len(self.player_skills),
            "has_password_puzzle": bool(self.target_hash),
            "player_coins": self.player_coins,
            "password_attempts": self.password_attempts
        }


def load_custom_game(json_data: Dict[str, Any]) -> CustomGameLoader:
    """快速加载自定义游戏"""
    loader = CustomGameLoader()
    loader.load_from_json(json_data)
    return loader


if __name__ == "__main__":
    # 测试用例
    test_data = {
        "maze": [
            ["#", "#", "#", "#", "#"],
            ["#", "S", " ", "G", "#"],
            ["#", "T", "#", "B", "#"],
            ["#", "L", " ", "E", "#"],
            ["#", "#", "#", "#", "#"]
        ],
        "C": [[1, 0], [-1, -1]],
        "B": [40, 60],
        "PlayerSkills": [[10, 2], [15, 3]],
        "L": "003a44b04e2e9eac5eb7597955068e745d78bb18b17a60d26645beebe111de40"
    }
    
    print("=== 自定义游戏加载器测试 ===")
    loader = load_custom_game(test_data)
    print("\n📊 游戏总结:", loader.get_game_summary()) 